import tkinter as tk
from tkinter import ttk

import matplotlib
# 配置matplotlib支持中文
matplotlib.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei', 'DejaVu Sans']  # 指定默认字体
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure


class HistoryDetailFrame(ttk.LabelFrame):
    def __init__(self, master):
        super().__init__(master, text="历史详情", width=400,padding=10)
        self._build_ui()

    def _build_ui(self):
        self.param_label = tk.Label(self, text="请选择一条历史记录", anchor="w", justify=tk.LEFT)
        self.param_label.pack(fill=tk.X, padx=5, pady=5)
        # self.data_text = tk.Text(self, height=8, font=("Consolas", 10))
        # self.data_text.pack(fill=tk.X, padx=5, pady=5)
        # save_btn = ttk.Button(self, text="保存数据修改", command=self.save_data_edit)
        # save_btn.pack(pady=2)
        # 创建两个子图：原始数据和对数数据
        self.fig = Figure(figsize=(8,6), dpi=100)
        self.ax1 = self.fig.add_subplot(211)  # 上方图表：原始数据
        self.ax2 = self.fig.add_subplot(212)  # 下方图表：对数数据
        self.fig.tight_layout(pad=3.0)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        canvas_widget = self.canvas.get_tk_widget()
        canvas_widget.config(width=700, height=600)
        canvas_widget.pack(padx=5, pady=5)

    def show_record(self, record):
        self._current_record = record
        param_text = f"测试时间: {record['time']}\n备注: {record.get('remark', '')}\n参数: {record.get('params', {})}"
        self.param_label.config(text=param_text)
        # 显示数据内容
        import json
        # self.data_text.delete(1.0, tk.END)
        # self.data_text.insert(tk.END, json.dumps(record.get('data', {}), ensure_ascii=False, indent=2))
        self.ax1.clear()
        self.ax2.clear()
        data = record.get('data', {})
        channel_order = record.get('channel_order', None)
        
        # 检查数据结构，兼容新旧格式
        if isinstance(data, dict) and 'original' in data and 'log' in data:
            # 新格式：包含原始数据和对数数据
            original_data = data['original']
            log_data = data['log']
        else:
            # 旧格式：只有一组数据，假设为原始数据
            original_data = data
            log_data = {}
            # 为旧数据计算对数值
            import math
            for ch, vals in original_data.items():
                log_vals = []
                for val in vals:
                    try:
                        log_val = math.log10(abs(val)) if val != 0 else float('-inf')
                    except Exception:
                        log_val = float('-inf')
                    log_vals.append(log_val)
                log_data[ch] = log_vals
        
        # 绘制原始数据图表
        colors = ['blue', 'red', 'green', 'orange', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan']
        
        # 检查是否为新的数据格式（包含遍数信息）
        def is_new_format(data):
            if not data:
                return False
            # 检查第一个通道的数据是否为字典格式（包含遍数）
            first_ch_data = next(iter(data.values()), None)
            return isinstance(first_ch_data, dict)
        
        original_is_new = is_new_format(original_data)
        log_is_new = is_new_format(log_data)
        
        if channel_order:
            # 如果有保存的通道顺序，按顺序显示
            channel_count = len([ch for ch in channel_order if ch > 0])
            for i in range(channel_count):
                physical_ch = str(i + 1)  # 物理通道号（字符串形式）
                # 从channel_order中提取通道号（低4位）
                logical_ch = (channel_order[i] & 0x0F) if i < len(channel_order) and channel_order[i] > 0 else i + 1
                
                # 绘制原始数据
                if physical_ch in original_data:
                    if original_is_new:
                        # 新格式：按遍数分组
                        rounds_data = original_data[physical_ch]
                        for round_no in sorted(rounds_data.keys()):
                            vals = rounds_data[round_no]
                            if vals:
                                round_no_int = int(round_no)  # 确保round_no是整数
                                color_idx = ((int(physical_ch) - 1) * 10 + (round_no_int - 1)) % len(colors)
                                line_style = '-' if round_no_int <= 5 else '--'
                                self.ax1.plot(range(len(vals)), vals, 
                                            label=f"通道{logical_ch}-第{round_no}遍",
                                            color=colors[color_idx],
                                            linestyle=line_style)
                    else:
                        # 旧格式：直接绘制
                        vals = original_data[physical_ch]
                        self.ax1.plot(range(len(vals)), vals, label=f"通道{logical_ch}")
                
                # 绘制对数数据
                if physical_ch in log_data:
                    if log_is_new:
                        # 新格式：按遍数分组
                        rounds_data = log_data[physical_ch]
                        for round_no in sorted(rounds_data.keys()):
                            log_vals = rounds_data[round_no]
                            if log_vals:
                                round_no_int = int(round_no)  # 确保round_no是整数
                                color_idx = ((int(physical_ch) - 1) * 10 + (round_no_int - 1)) % len(colors)
                                line_style = '-' if round_no_int <= 5 else '--'
                                self.ax2.plot(range(len(log_vals)), log_vals, 
                                            label=f"通道{logical_ch}-第{round_no}遍",
                                            color=colors[color_idx],
                                            linestyle=line_style)
                    else:
                        # 旧格式：直接绘制
                        log_vals = log_data[physical_ch]
                        self.ax2.plot(range(len(log_vals)), log_vals, label=f"通道{logical_ch}")
        else:
            # 兼容旧数据，按默认顺序显示
            for ch, data_item in original_data.items():
                if original_is_new:
                    # 新格式：按遍数分组
                    for round_no in sorted(data_item.keys()):
                        vals = data_item[round_no]
                        if vals:
                            round_no_int = int(round_no)  # 确保round_no是整数
                            color_idx = ((int(ch) - 1) * 10 + (round_no_int - 1)) % len(colors)
                            line_style = '-' if round_no_int <= 5 else '--'
                            self.ax1.plot(range(len(vals)), vals, 
                                        label=f"通道{ch}-第{round_no}遍",
                                        color=colors[color_idx],
                                        linestyle=line_style)
                else:
                    # 旧格式：直接绘制
                    self.ax1.plot(range(len(data_item)), data_item, label=f"通道{ch}")
            
            for ch, data_item in log_data.items():
                if log_is_new:
                    # 新格式：按遍数分组
                    for round_no in sorted(data_item.keys()):
                        log_vals = data_item[round_no]
                        if log_vals:
                            round_no_int = int(round_no)  # 确保round_no是整数
                            color_idx = ((int(ch) - 1) * 10 + (round_no_int - 1)) % len(colors)
                            line_style = '-' if round_no_int <= 5 else '--'
                            self.ax2.plot(range(len(log_vals)), log_vals, 
                                        label=f"通道{ch}-第{round_no}遍",
                                        color=colors[color_idx],
                                        linestyle=line_style)
                else:
                    # 旧格式：直接绘制
                    self.ax2.plot(range(len(data_item)), data_item, label=f"通道{ch}")
        
        # 设置图表标题和标签
        self.ax1.set_title("原始数据")
        self.ax1.legend()
        self.ax1.set_xlabel("采样点")
        self.ax1.set_ylabel("电流 I")
        
        self.ax2.set_title("对数数据")
        self.ax2.legend()
        self.ax2.set_xlabel("采样点")
        self.ax2.set_ylabel("对数电流 Log(I)")
        
        self.canvas.draw()

    def save_data_edit(self):
        import json
        try:
            new_data = json.loads(self.data_text.get(1.0, tk.END))
        except Exception as e:
            tk.messagebox.showerror("格式错误", f"JSON解析失败: {e}")
            return
        # 更新数据库
        from history_db import update_remark, add_record, get_all_records
        # 这里只能通过重新插入一条新记录或扩展db接口来支持数据更新，建议扩展db接口
        # 这里假设有update_data接口
        from history_db import update_data
        update_data(self._current_record['id'], new_data)
        self._current_record['data'] = new_data
        self.show_record(self._current_record)
        tk.messagebox.showinfo("成功", "数据已更新")